var defaultPage = Public.getDefaultPage();
var config = defaultPage.CONFIG;
var system = defaultPage.SYSTEM;
var wt_type = $("#wt_type").val();
var api = frameElement.api, W = api.opener;
var callback = api.data.callback,oper = api.data.oper;
var _height = $(parent).height()-262,_width = $(parent).width()-2;

var Utils = {
	doQueryProduct : function(){
		commonDia = $.dialog({
			title : '选择商品',
			content : 'url:'+config.BASEPATH+'wx/product/to_select_product',
			data : {multiselect:true},
			width : 860,
			height : 420,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				Utils.addGridData(selected);
			},
			close:function(){
			},
			cancel:true
		});
	},
	addGridData:function(selected){
		var products = [];
		var price_rate = $("#price_rate").val();
		if(price_rate == '' || isNaN(price_rate) || parseFloat(price_rate) < 0){
			price_rate = 1;
		}else{
			price_rate = parseFloat(price_rate);
		}
		for(var i=0;i<selected.length;i++){
			var product = {};
			product.pd_code = selected[i].pd_code;
			product.pd_no = selected[i].pd_no;
			product.pd_name = selected[i].pd_name;
			product.wp_sell_price = selected[i].pd_sell_price;
			product.wp_rate_price = selected[i].pd_sell_price * price_rate;
			product.bd_name = selected[i].pd_bd_name;
			product.pd_season = selected[i].pd_season;
			product.pd_year = selected[i].pd_year;
			product.pd_style = selected[i].pd_style;
			product.pd_fabric = selected[i].pd_fabric;
			product.wp_virtual_amount = 0;
			product.wp_buy_limit = 0;
			product.wp_subtitle = '';
			products.push(product);
		}
		var ids = $("#grid").jqGrid('getDataIDs');
		var exist = false;
		for(var i=0;i<products.length;i++){
			var product = products[i];
			exist = false;
			for(var j=0;j < ids.length;j++){
				var rowData = $('#grid').jqGrid('getRowData',ids[j]);
				if(rowData.pd_code == product.pd_code){
					exist = true;
					break;
				}
			}
			if(!exist){
				$("#grid").addRowData(product.pd_code, product,'first');
			}
		}
	},
	doQueryShop : function(){
		commonDia = $.dialog({
			title : '选择店铺',
			content : 'url:'+config.BASEPATH+'base/shop/list_dialog_bymodule',
			data : {multiselect:true,module:'wxproduct'},
			width : 490,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].sp_code);
					names.push(selected[i].sp_name);
				}
				$("#shop_codes").val(codes.join(","));
				$("#shop_names").val(names.join(","));
				return true;
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryProductType : function(){
		commonDia = $.dialog({
			title : '选择商品分类',
			content : 'url:'+config.BASEPATH+'wx/producttype/to_tree_dialog',
			data : {multiselect:false},
			width : 360,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : "请选择商品类别！"});
					return false;
				}
				if (selected.pt_code == "0") {
					Public.tips({type: 2, content : "请选择具体商品类别！"});
					return false;
				}
				$("#wp_pt_code").val(selected.pt_code);
				$("#pt_name").val(selected.pt_name);
			},
			close:function(){
				if(commonDia.content.dblClick){//双击关闭
					var selected = commonDia.content.doSelect();
					if (selected.pt_code == "0") {
						Public.tips({type: 2, content : "请选择具体商品类别！"});
						return false;
					}
					$("#wp_pt_code").val(selected.pt_code);
					$("#pt_name").val(selected.pt_name);
				}
			},
			cancel:true
		});
	},
	doQueryProperty : function(){
		commonDia = $.dialog({
			title : '选择商品属性',
			content : 'url:'+config.BASEPATH+'common/dict/to_list_dialog',
			data : {multiselect:true,dt_type:'PRODUCT_PROPERTY'},
			width : 380,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : "请选择商品属性！"});
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].dt_code);
					names.push(selected[i].dt_name);
				}
				$("#wp_property_code").val(codes.join(","));
				$("#property_name").val(names.join(","));
				return true;
			},
			close:function(){
			},
			cancel:true
		});
	},
	doQueryPromise : function(){
		commonDia = $.dialog({
			title : '选择售后承诺',
			content : 'url:'+config.BASEPATH+'common/dict/to_list_dialog',
			data : {multiselect:true,dt_type:'PRODUCT_PROMISE'},
			width : 380,
			height : 320,
			max : false,
			min : false,
			cache : false,
			lock: true,
			ok:function(){
				var selected = commonDia.content.doSelect();
				if (!selected) {
					Public.tips({type: 2, content : "请选择商品属性！"});
					return false;
				}
				var codes = [];
				var names = [];
				for(var i=0;i<selected.length;i++){
					codes.push(selected[i].dt_code);
					names.push(selected[i].dt_name);
				}
				$("#wp_promise_code").val(codes.join(","));
				$("#promise_name").val(names.join(","));
				return true;
			},
			close:function(){
			},
			cancel:true
		});
	}
};

var handle = {
	save:function(){
		var products = [];
		var ids = $("#grid").jqGrid('getDataIDs');
		for(var i = 0;i < ids.length; i++){
			if(ids[i] == 0){
				continue;
			}
			var rowData = $('#grid').jqGrid('getRowData',ids[i]);
			var product = {};
			product.wp_pd_code = rowData.pd_code;
			product.wp_pd_name = rowData.pd_name;
			product.wp_sell_price = rowData.wp_sell_price;
			product.wp_rate_price = rowData.wp_rate_price;
			product.wp_subtitle = rowData.wp_subtitle;
			product.wp_virtual_amount = rowData.wp_virtual_amount;
			product.wp_buy_limit = rowData.wp_buy_limit;
			products.push(product);
		}
		if(products.length == 0){
			Public.tips({type: 2, content : '请选择商品货号！'});
			return;
		}
		var mainInfo = {};
		mainInfo.wp_pt_code = $("#wp_pt_code").val();
		mainInfo.wp_property_code = $("#wp_property_code").val();
		mainInfo.wp_promise_code = $("#wp_promise_code").val();
		mainInfo.shop_codes = $("#shop_codes").val();
		mainInfo.wp_type = $("#wp_type").val();
		if(mainInfo.wp_pt_code == ''){
			Public.tips({type: 2, content : '请选择商品分类！'});
			return;
		}
		if(mainInfo.wp_property_code == ''){
			Public.tips({type: 2, content : '请选择商品属性！'});
			return;
		}
		if(mainInfo.wp_promise_code == ''){
			Public.tips({type: 2, content : '请选择售后承诺！'});
			return;
		}
		if(mainInfo.shop_codes == ''){
			Public.tips({type: 2, content : '请选择关联店铺！'});
			return;
		}
		var wp_istry = $("#wp_istry").val();
		var wp_isbuy = $("#wp_isbuy").val();
		var wp_try_way = '';
		if(wp_istry == '1'){//允许试穿-获得试穿取货方式
			if(THISPAGE.$_wp_try_way_0.chkVal().join()){
				wp_try_way += '0,';
			}
			if(THISPAGE.$_wp_try_way_1.chkVal().join()){
				wp_try_way += '1,';
			}
			if(wp_try_way.length > 0){
				wp_try_way = wp_try_way.substring(0, wp_try_way.length-1);
	    	}else{
	    		Public.tips({type: 2, content : '请选择试穿方式！'});
				return;
	    	}
		}
		var wp_buy_way = '';
		var wp_postfree = '';
		if(wp_isbuy == '1'){//允许购买-获得购买取货方式
			if(THISPAGE.$_wp_buy_way_0.chkVal().join()){
				wp_buy_way += '0,';
				if(THISPAGE.$_wp_postfree.chkVal().join()){
					wp_postfree = '1';
				}else{
					wp_postfree = '0';
				}
			}
			if(THISPAGE.$_wp_buy_way_1.chkVal().join()){
				wp_buy_way += '1,';
			}
			if(wp_buy_way.length > 0){
				wp_buy_way = wp_buy_way.substring(0, wp_buy_way.length-1);
	    	}else{
	    		Public.tips({type: 2, content : '请选择购买取货方式！'});
				return;
	    	}
		}
		mainInfo.wp_istry = wp_istry;
		mainInfo.wp_try_way = wp_try_way;
		mainInfo.wp_isbuy = wp_isbuy;
		mainInfo.wp_buy_way = wp_buy_way;
		mainInfo.wp_postfree = wp_postfree;
		for (var i = 0; i < products.length; i++) {
			products[i].wp_type = mainInfo.wp_type;
			products[i].wp_pt_code = mainInfo.wp_pt_code;
			products[i].wp_istry = mainInfo.wp_istry;
			products[i].wp_try_way = mainInfo.wp_try_way;
			products[i].wp_isbuy = mainInfo.wp_isbuy;
			products[i].wp_buy_way = mainInfo.wp_buy_way;
			products[i].wp_postfree = mainInfo.wp_postfree;
			products[i].wp_property_code = mainInfo.wp_property_code;
			products[i].wp_promise_code = mainInfo.wp_promise_code;
			products[i].shop_codes = mainInfo.shop_codes;
		}
		$("#btn-save").attr("disabled",true);
		$.ajax({
			type:"POST",
			url:config.BASEPATH+"wx/product/save",
			data:{products:Public.encodeURI(JSON.stringify(products))},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					Public.tips({type: 3, content : '保存成功'});
					handle.loadData(data.data);
				}else{
					Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").attr("disabled",false);
			}
		});
	},
	loadData:function(data){
		if(callback && typeof callback == 'function'){
			callback({},oper,window);
		}
	},
	operFmatter :function(val, opt, row){
		var html_con = '<div class="operating" data-id="' +opt.rowId+ '">';
		html_con += '<i class="iconfont i-hand ui-icon-plus" title="增加">&#xe639;</i>';
		html_con += '<i class="iconfont i-hand ui-icon-trash" title="删除">&#xe60e;</i>';
		html_con += '</div>';
		return html_con;
	}
};

var THISPAGE = {
	init:function (){
		this.initDom();
		this.initGrid();
		this.initEvent();
	},
	initDom:function(){
		this.selectRow={};
		this.$_wp_type = $("#td_wp_type").cssRadio({ callback: function($_obj){
			$("#wp_type").val($_obj.find("input").val());
		}});
		this.$_wp_istry = $("#td_wp_istry").cssRadio({ callback: function($_obj){
			var wp_istry = $_obj.find("input").val();
			$("#wp_istry").val(wp_istry);
			if(wp_istry == '0'){
				$("#wp_try_way_0").hide();
				$("#wp_try_way_1").hide();
			}else if(wp_istry == '1'){
				$("#wp_try_way_0").show();
				$("#wp_try_way_1").show();
			}
		}});
		this.$_wp_try_way_0 = $("#wp_try_way_0").cssCheckbox({ callback: function($_obj){
        	if($_obj.find("input")[0].checked){//选中
        	}else{//取消
        	}
		}});
		this.$_wp_try_way_1 = $("#wp_try_way_1").cssCheckbox({ callback: function($_obj){
        	if($_obj.find("input")[0].checked){//选中
        	}else{//取消
        	}
		}});
		this.$_wp_isbuy = $("#td_wp_isbuy").cssRadio({ callback: function($_obj){
			var wp_isbuy = $_obj.find("input").val();
			$("#wp_isbuy").val(wp_isbuy);
			if(wp_isbuy == '0'){
				$("#wp_buy_way_0").hide();
				$("#wp_buy_way_1").hide();
				$("#wp_postfree").hide();
			}else if(wp_isbuy == '1'){
				$("#wp_buy_way_0").show();
				$("#wp_buy_way_1").show();
				if(THISPAGE.$_wp_buy_way_0.chkVal().join()){
					$("#wp_postfree").show();
				}
			}
		}});
		this.$_wp_buy_way_0 = $("#wp_buy_way_0").cssCheckbox({ callback: function($_obj){
        	if($_obj.find("input")[0].checked){//选中
        		$("#wp_postfree").show();
        	}else{//取消
        		$("#wp_postfree").hide();
        	}
		}});
		this.$_wp_buy_way_1 = $("#wp_buy_way_1").cssCheckbox({ callback: function($_obj){
        	if($_obj.find("input")[0].checked){//选中
        	}else{//取消
        	}
		}});
		this.$_wp_postfree = $("#wp_postfree").cssCheckbox({ callback: function($_obj){
			if($_obj.find("input")[0].checked){//选中
			}else{//取消
			}
		}});
	},
	addEmptyData:function(){
    	var emptyData = {pd_code:''};
    	$("#grid").addRowData(0, emptyData);
    },
	initGrid:function(){
		var self=this;
		var colModel = [
		    {label:'操作',name:'operate', width: 60, fixed:true, formatter: handle.operFmatter, sortable:false,align:'center'},
		    {label:'',name: 'pd_code', index: 'pd_code', hidden:true},
	    	{label:'商品货号',name: 'pd_no', index: 'pd_no', width: 100},
	    	{label:'商品名称',name: 'pd_name', index: 'pd_name', width: 100},
	    	{label:'零售价',name: 'wp_sell_price', index: 'wp_sell_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'折扣价',name: 'wp_rate_price', index: 'wp_rate_price', width: 80,align:'right',sorttype: 'float',formatter: PriceLimit.formatMoney,editable:true},
	    	{label:'品牌',name: 'bd_name', index: 'bd_name', width: 60},
	    	{label:'季节',name: 'pd_season', index: 'pd_season', width: 60},
	    	{label:'年份',name: 'pd_year', index: 'pd_year', width: 60},
	    	{label:'款式',name: 'pd_style', index: 'pd_style', width: 60},
	    	{label:'面料',name: 'pd_fabric', index: 'pd_fabric', width: 60},
	    	{label:'虚拟销售',name: 'wp_virtual_amount', index: 'wp_virtual_amount', width: 70,align:'right',sorttype: 'int',editable:true},
	    	{label:'限购数量',name: 'wp_buy_limit', index: 'wp_buy_limit', width: 70,align:'right',sorttype: 'int',editable:true},
	    	{label:'副标题',name: 'wp_subtitle', index: 'wp_subtitle', width: 240,editable:true}
	    ];
		$('#grid').jqGrid({
			datatype: 'local',
			width: _width,
			height: _height,
			gridview: true,
			colModel: colModel,
			rownumbers: true,//行号
			pager: '#page',//分页
			pgbuttons:false,
			page:1,
			pgtext:false,
			recordtext:'共 {2} 条', 
			multiselect:false,//多选
			viewrecords: true,
			rowNum:9999,//每页条数
			cmTemplate: {sortable:true,title:true},
			shrinkToFit:false,//表格是否自动填充
			cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
			jsonReader: {
				root: 'data', 
				repeatitems : false,
				id: 'id'  //图标ID
			},
			loadComplete: function(data){
				THISPAGE.addEmptyData();
			},
			loadError: function(xhr, status, error){		
			},
			ondblClickRow:function(rowid,iRow,iCol,e){
				handle.temp_update(rowid, '0');
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
            	self.selectRow.value=value;
				return value;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				if(rowid == 0){
					return '';
				}
				if(self.selectRow.value == value){
					return value;
				}
				if(cellname == 'wp_subtitle'){
					if(value.length > 30){
						Public.tips({type: 2, content : '副标题不能超过30个字！'});
						return self.selectRow.value;
					}
					return value;
				}else if(cellname == 'wp_sell_price' || cellname == 'wp_rate_price'){
					if(value == '' || isNaN(value) || parseFloat(value) <= 0){
						return self.selectRow.value;
					}
					if(parseFloat(self.selectRow.value) == parseFloat(value)){
						return self.selectRow.value;
					}
					if(parseFloat(value).toFixed(0).length > 9|| parseInt(value) >1e+9){
						return self.selectRow.value;
					}
					return parseFloat(value).toFixed(2);
				}else if(cellname == 'wp_virtual_amount' || cellname == 'wp_buy_limit'){
					if(value == '' || isNaN(value) || parseFloat(value) <= 0){
						return self.selectRow.value;
					}
					if(parseInt(self.selectRow.value) == parseInt(value)){
						return self.selectRow.value;
					}
					if(parseInt(value).toFixed(0).length > 9|| parseInt(value) >1e+9){
						return self.selectRow.value;
					}
					return parseInt(value);
				}
				return value;
			}
	    });
	},
	initEvent:function(){
		$('#btn-save').on('click', function(e){
			e.preventDefault();
			handle.save();
		});
		$("#btn_close").click(function(e){
			e.preventDefault();
			api.close();
		});
        //修改-列表模式
        $('#grid').on('click', '.operating .ui-icon-plus', function (e) {
        	e.preventDefault();
        	Utils.doQueryProduct();
        });
        //删除-列表模式
		$('#grid').on('click', '.operating .ui-icon-trash', function(e) {
			e.preventDefault();
			var id = $(this).parent().data('id');
			$.dialog.confirm('数据删除后无法恢复，确定要清除吗？', function(){
				$('#grid').jqGrid('delRowData', id);
			});
		});
	}
};

THISPAGE.init();